package io.p2p.stream.stun.task;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.stun.util.BuildPacketsUtil;
import io.p2p.stream.stun.util.UniqueIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class MainServerHeartbeatTask implements Runnable  {
    private String senderName;
    private String targetHost;
    private int targetPort;
    private Channel channel;

    public MainServerHeartbeatTask(String senderName, String targetHost,
                                   int targetPort, Channel channel){
        log.info("Enable Heartbeat Monitoring with the Main Service on ip: {},port:{}"
                ,targetHost,targetPort);
        this.targetHost = targetHost;
        this.targetPort = targetPort;
        this.senderName = senderName;
        this.channel = channel;
    }

    @Override
    public void run() {
        //发送心跳指令给main服务
        JSONObject heartbeatMsg = new JSONObject();
        heartbeatMsg.put("name", senderName);
        heartbeatMsg.put("type","mainlineHeartbeat");
        heartbeatMsg.put("time",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        heartbeatMsg.put("msg","Mainline UDP Client Service heartbeat message.");

        log.info("Send to Main UDP Server Heartbeat: {}",heartbeatMsg);

        long seqNum = UniqueIdGeneratorUtil.getInstance().getUniqueId();
        channel.writeAndFlush(new DatagramPacket(BuildPacketsUtil.wrap(seqNum,heartbeatMsg.toJSONString()),
                new InetSocketAddress(targetHost,targetPort)));
    }
}
